<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		getUrl,
		confirmModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		changeConfigAttr ,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	export default {
		provide() {
			return {
				formPage: this
			};
		},
		data() {
			return buildFormData({
				projectCacheKey: "hr-train-trainNotice-project-cache",
				relevantAbilityCacheKey: "hr-train-trainNotice-relevantAbility-cache",
				partakeUserCache:"hr-train-trainNotice-partakeUser-cache",
				userCacheKey:'hr-train-trainNotice-user-cache',
				currencyCacheKey:'hr-train-trainNotice-currency-cache',
				teacherCacheKey:'hr-train-trainNotice-teacher-cache',
				defaultDataCache:'hr-train-trainNotice-defaultData-cache'
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		methods: {
			formSubmit(){
				let _that = this
				if(_that.edit){
					_that.om.formSave("trainNotice/doUpdate",_that.formdata._that)
				}else{
					_that.om.formSave('trainNotice/doAdd',_that.formdata,_that)
				}
			},
			getWorkParam(){
				let _that = this 
				return {
					relevantAbilityIdStr:_that.$refs.autoform.formdata.relevantAbilityIdStr
				}
			},
			intLoad(options) {
				let _that = this
				let ajaxArr = [
					urlUtil.zposUrl(options.code),
					urlUtil.sysdictComboboxUrl("38404"),
					urlUtil.sysdictComboboxUrl("38577"),
					urlUtil.sysdictComboboxUrl("38562"),
					{
						url:'/dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'7042'
						}
					}
				]
				let fileId = options.fileId
				if(fileId){
					ajaxArr.push({
						url:"trainNotice/getValue",
						param:{
							fileId:fileId
						}
					})
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					changeEditor("topinfo", "zposId", "data", configSelectData(res[0], "id", "posname"), mainData)
					changeEditor("title1", "trainTypeId", "data", configSelectData(res[1], "id", "dicname"), mainData)
					changeEditor("title1", "trainEvaluationTypeId", "data", configSelectData(res[2], "id", "dicname"), mainData)
					changeEditor("title1", "projectTypeId", "data", configSelectData(res[3], "id", "dicname"), mainData)
					changeEditor("title1", "trainModeId", "data", configSelectData(res[4], "id", "text"), mainData)
					changeConfigAttr("title1", "showButton", true,mainData)
					changeConfigAttr("title1", "buttonText", "培训视频页",mainData)
					changeConfigAttr("title1", "buttonLink",
						"/pages/mine/video/video-type",mainData)
					changeEditor("title1", "projectId", {
						link: "../../public/pageSearch/pageSearch",
						"linkParam": {
							other: JSON.stringify({}),
							namefield: "projectName",
							extrafield: "projectCode",
							notefield: "trainTypeName",
							searchfield: "q",
							initload: true,
							url: "trainNotice/likeSerchShow",
							cachename: _that.projectCacheKey
						}
					}, null, mainData)
					changeEditor("title1","userId",{
						link:'../../public/searchUser/searchUser',
						"linkParam":{
							cachename: _that.userCacheKey,
							isSingle:true
						}
					},null,mainData)
					changeEditor("title1_4","partakeUserIdStr", {
						'link':'../../public/searchUser/searchUser',
						linkParam: {
							namefield: urlUtil.userPageUrl().namefield,
							searchfield: "q",
							cachename: _that.partakeUserCache,
							defaultDataCache:_that.defaultDataCache,
							isNew:true,
							placeholder: urlUtil.userPageUrl().prompt,
							pagination: true
						}
					}, null, mainData);
					changeEditor('title1','relevantAbilityIdStr', {
						"linkParam": {
							other: JSON.stringify({
								code: '35905'
							}),
							namefield: 'text',
							likefield: 'text',
							initload: true,
							url: '/tsysdict/getComboTree',
							cachename: _that.relevantAbilityCacheKey
						}
					}, null, mainData);
					
					changeEditor('title1','currencyNameId', {
						link:'../../public/pageSearch/pageSearch',
						"linkParam": {
							other: JSON.stringify({
							}),
							namefield: 'codeNameUnit',
							initload: true,
							url: 'currencyDict/getCurrency',
							cachename: _that.currencyCacheKey
						}
					}, null, mainData);
					changeEditor('title1', 'teacherId', {
						'link':'../../public/searchUser/searchUser',
						linkParam: {
							namefield: urlUtil.userPageUrl().namefield,
							searchfield: "q",
							cachename: _that.teacherCacheKey,
							isSingle:true,
							isNew:true,
							placeholder: urlUtil.userPageUrl().prompt,
							pagination: true
						}
					}, null, mainData);
					if(_that.subEditorObj["title2"]){
						changeEditor("title2","dataStr",{
							getWorkParam:"getWorkParam",
							titleTemplate:"<%= '课程名称:' + dataContent %>",
							subtitle1Template:"<%= '课节数:' + dataSort %>|<%='时长:'+ dataTimeNum %>"
						},null,mainData)
					}
					if(fileId){
						let fieldArr = getFormFields(mainData)
						fieldArr.push("id")
						for(let index in res[4].value){
							if(fieldArr.includes(index)){
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[4].value[index])
								_that.$set(_that.formdata,index,res[4].value[index])
							}
						}
						let dataList = _that._.cloneDeep(res[4].value.dataList)
						_that.subEditorObj["title2"].workList = dataList
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata,"dataStr",JSON.stringify(dataList))
						_that.$set(_that.formdata,"dataStr",JSON.stringify(dataList))
						delete res[4].value.dataList
						
						_that.$nextTick(function(){
							_that.$refs.autoform.initSelectIndex("topinfo","zposId")
							_that.$refs.autoform.initSelectIndex('title1',"trainTypeId")
							_that.$refs.autoform.initSelectIndex('title1',"trainEvaluationTypeId")
							_that.$refs.autoform.initSelectIndex("title1", "projectTypeId")
						})
					}
					_that.$nextTick(function(){
						if(!_that.$refs.autoform.formdata.zposId){
							_that.$refs.autoform.initSelectVal("topinfo","zposId")
						}
					})
				},options)
			}
		},
		onLoad(options) {
			let _that = this
			_that.intLoad(options)
		},
		
		onUnload(){
			let _that = this;
			uni.removeStorage({
				key:_that.defaultDataCache
			})
			//#ifdef APP-PLUS
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
			//#endif
		},
		onShow() {
			let _that = this
				if (_that.$refs.autoform) {
					for (var fieldId in _that.subEditorObj) {
						let editor = _that.subEditorObj[fieldId];
						uni.getStorage({
							key: getWorkCacheKey(fieldId),
							success: function(res) {
								editor.workList = res.data;
								for(let obj of editor.workList){
									obj.startDate = obj.startDate + ":" + "00"
								}
								uni.removeStorage({
									key: getWorkCacheKey(fieldId)
								});
							}
						});
					}
				}
				try {
					const d = uni.getStorageSync(_that.projectCacheKey);
					uni.removeStorage({
						key:_that.projectCacheKey
					})
					if (d) {
						let formdata = _that.$refs.autoform.formdata
						formdata.projectOrderNum = d.orderNum
						formdata.userId = d.userId
						formdata.userName = d.userName
						formdata.projectTypeName = d.projectTypeName
						formdata.projectTypeId = d.projectTypeId
						_that.$refs.autoform.initSelectIndex("title1", "projectTypeId")
						formdata.trainTypeName = d.trainTypeName
						formdata.projectName = d.projectName
						formdata.startDate = d.startDate
						formdata.timeNum = d.timeNum
						formdata.partakeUserNum = d.partakeUserNum
						formdata.relevantAbilityIdStr = d.relevantAbilityIdStr||''
						formdata.relevantAbilityNameStr = d.relevantAbilityNameStr
						formdata.trainTypeName = d.trainTypeName
						formdata.trainTypeId = d.trainTypeId
						formdata.startDate = d.startDate
						formdata.content = d.content || ''
						formdata.trainObj = d.trainObj
						_that.$refs.autoform.initSelectIndex('title1',"trainTypeId")
						formdata.trainModeId = d.trainModeId
						formdata.trainModeName = d.trainModeName
						_that.$refs.autoform.initSelectIndex('title1',"trainModeId")
						formdata.startDateObjId = d.startDateObjId
						formdata.startDateObjName = d.startDateObjName
						formdata.endDateObjId = d.endDateObjId
						formdata.endDateObjName = d.endDateObjName
						formdata.currencyNameId = d.currencyNameId
						formdata.currencyName = d.currencyName
						formdata.totalCost = d.totalCost
						formdata.teacherId = d.teacherId
						formdata.teacherName = d.teacherName
						_that.om.request(
							"tsysdict/getComboTree", {
								code: "35905"
							}
						).then(res => {
							let newArr = []
							if(d.relevantAbilityIdStr != null){
								let relevantAbilityArr = d.relevantAbilityIdStr.split(",")
								for(let obj of res){
									if(relevantAbilityArr.indexOf(obj.id+"") > -1){
										newArr.push(obj)
									}
								}
								_that.$refs.autoform.changeEditor('title1', 'relevantAbilityIdStr', {
									initSelect: newArr
								})
							}
						})
					}
					
				} catch (e) {
					// error
				}
				uni.getStorage({
					key:_that.relevantAbilityCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.relevantAbilityIdStr = d.map(e =>e.id).join(",")
							formdata.relevantAbilityNameStr = d.map(e =>e.text).join(",")
							_that.$refs.autoform.changeEditor('title1', 'relevantAbilityIdStr', {
								initSelect: d
							})
							uni.removeStorage({
								key:_that.relevantAbilityCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key:_that.userCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data[0]
							let formdata = _that.$refs.autoform.formdata
							formdata.userId = d.id
							formdata.userName = d.username
							uni.removeStorage({
								key:_that.userCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key:_that.teacherCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data[0]
							let formdata = _that.$refs.autoform.formdata
							formdata.teacherId = d.id
							formdata.teacherName = d.username
							uni.removeStorage({
								key:_that.teacherCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key:_that.partakeUserCache,
					success:(res)=>{
						if(res.data){
							let d = res.data;
							uni.setStorage({
								key:_that.defaultDataCache,
								data:d
							})
							var formdata = _that.$refs.autoform.formdata;
							if(d.length){
								let idList = []
								let nameList = []
								let user3Id = ''
								for(let index in d){
									idList.push(d[index].id)
									nameList.push(d[index].username)
								}
								
								let idStr = idList.map(e =>e).join(",")
								let nameStr = nameList.map(e =>e).join(",");
								
								formdata.partakeUserIdStr = idStr
								formdata.partakeUserNameStr = nameStr
							}
							uni.removeStorage({
								key: _that.partakeUserCache
							});
						}
					}
				})
		}
	}
</script>

<style>
</style>
